package com.wan37.gate.server;

import com.wan37.gate.handler.GateToLogicConnectionHandler;
import com.wan37.protobuf.codec.ProtoPacketDecoder;
import com.wan37.protobuf.codec.ProtoPacketEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author : luoyong
 * @date : 2020-05-27 12:33
 **/
public class GateToLogicConnection implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(GateToLogicConnection.class);
    /**
     * LogicServer的ip
     */
    private String logicIp;

    /**
     * LogicServer的端口
     */
    private int logicPort;

    public GateToLogicConnection(String logicIp, int logicPort) {
        this.logicIp = logicIp;
        this.logicPort = logicPort;
    }

    @Override
    public void run() {
        this.buildGateToLogicConnection();
    }

    public void buildGateToLogicConnection() {
        /**
         * 使用Netty框架建立一条Gate网关服务器到Logic逻辑服务器的连接。
         * 在这里：
         * Gate是 客户端角色, Logic是 服务器角色。
         */
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast("LenthFieldBasedFrameDecoder",
                                new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,
                                        0,
                                        4,
                                        4,
                                        0));

                        pipeline.addLast("ProtobufPacketDecoder", new ProtoPacketDecoder());

                        pipeline.addLast("GateToLogicConnectionHandler", new GateToLogicConnectionHandler());

                        pipeline.addLast("ProtobufPacketEncoder", new ProtoPacketEncoder());
                    }
                });

        ChannelFuture future = bootstrap.connect(this.logicIp, this.logicPort);
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (future.isSuccess()) {
                    logger.info("[GateToLogicConnection] 连接建立成功！");
                } else {
                    logger.error("[GateToLogicConnection] 连接建立失败!");
                }
            }
        });
    }
}
